package com.webwork.mood.record.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.webwork.mood.common.dao.impl.SimpleDao;
import com.webwork.mood.record.dao.DrawDateDao;
import com.webwork.mood.util.ColumnLimit;
import com.webwork.mood.util.DBSimpleSQL;

@Repository
public class DrawDateDaoImpl extends SimpleDao implements DrawDateDao {

	public DrawDateDaoImpl() {
		super();
		this.dbTable = "t_draw_date";
		dbColumns.clear();
		dbColumns.put("date", "DATE");
	}
	
	@Override
	public ColumnLimit condition(Object object) {
		if (!(object instanceof Integer))
			return new ColumnLimit();
		Integer o = (Integer) object;
		ColumnLimit ret = new ColumnLimit();
		if (o != 0) {
			ret.add(dbColumns.get("date") + " = ");
		}
		return ret;
	}

	@Override
	public Object[] statement(Object object) {
		Integer o = (Integer) object;
		List<Object> ret = new ArrayList<Object>();
		if (o != 0) {
			ret.add(o);
		}
		return ret.toArray();
	}

	@Override
	public List<Object> pushObject(Object object) {
		Integer o = (Integer) object;
		List<Object> objs = new ArrayList<Object>();
		objs.add(o);
		return objs;
	}

	@Override
	public Object catchObject(Map<String, Object> map) {
		return (Integer) map.get(dbColumns.get("date"));
	}
	
	@Override
	public void insert(int drawDate) {
		String sql = DBSimpleSQL.insert(dbTable, dbColumns.size());
		this.getJdbcTemplate().update(sql, this.pushObject(drawDate).toArray());
	}

	@Override
	public void update(int drawDate) {
		ColumnLimit limit = new ColumnLimit();
		limit.add(dbColumns.get("date") + " = ");
		String sql = DBSimpleSQL.update(dbTable, dbColumns, limit);
		List<Object> objs = this.pushObject(drawDate);
		objs.add(drawDate);
		this.getJdbcTemplate().update(sql, objs.toArray());
	}

	@Override
	public void delete(int drawDate) {
		ColumnLimit limit = new ColumnLimit();
		limit.add(dbColumns.get("date") + " = ");
		String sql = DBSimpleSQL.del(dbTable, limit);
		this.getJdbcTemplate().update(sql, drawDate);
	}
	
	@Override
	public List<Integer> query(int drawDate, int page, int size) {
		List<Integer> ret = new ArrayList<Integer>();
		String sql = DBSimpleSQL.selectAll(dbTable, this.condition(drawDate), page, size);
		List<Map<String, Object>> maps = this.getJdbcTemplate().queryForList(sql, this.statement(drawDate));
		for (Map<String, Object> map : maps) {
			ret.add((Integer) this.catchObject(map));
		}
		return ret;
	}

	@Override
	public int count(int drawDate) {
		String sql = DBSimpleSQL.count(dbTable, this.condition(drawDate));
		return this.getJdbcTemplate().queryForObject(sql, this.statement(drawDate), Integer.class);
	}
	
}
